<template>
  <el-row>
    <el-col :span="3">
      <el-card>
        <div v-for="(item,index) in majors" :key="index">
          <div class="popover-title"
               :style="{background:selectDictKey===item.dictKey?'#efe9e9':''}"
               @click="majorChanged(item)">{{ item.dictValue }}
          </div>
        </div>
      </el-card>
    </el-col>
    <el-col :span="21">
      <basic-container>
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   :page="page"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   v-model="form"
                   ref="crud"
                   @upload-error="uploadError"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @on-load="onLoad">

          <!-- 身份证 -->
          <template #idCard="{row}">
            <div v-if="row.idCard">
              <div v-for="item in JSON.parse(row.idCard)">
                <el-tooltip effect="light" placement="right">
                  <template #content>
                    <el-link type="primary" :underline="false" @click="handleClickTag(item.url)">下载</el-link>
                  </template>
                  <el-link type="primary" @click="openPreview(item.url)" :underline="false">{{ item.name }}</el-link>
                </el-tooltip>
              </div>
            </div>
          </template>

          <!-- 注册证书 -->
          <template #regCert="{row}">
            <div v-if="row.regCert">
              <div v-for="item in JSON.parse(row.regCert)">
                <el-tooltip effect="light" placement="right">
                  <template #content>
                    <el-link type="primary" :underline="false" @click="handleClickTag(item.url)">下载</el-link>
                  </template>
                  <el-link type="primary" @click="openPreview(item.url)" :underline="false">{{ item.name }}</el-link>
                </el-tooltip>
              </div>
            </div>
          </template>

          <!-- 职业证书 -->
          <template #profCert="{row}">
            <div v-if="row.profCert">
              <div v-for="item in JSON.parse(row.profCert)">
                <el-tooltip effect="light" placement="right">
                  <template #content>
                    <el-link type="primary" :underline="false" @click="handleClickTag(item.url)">下载</el-link>
                  </template>
                  <el-link type="primary" @click="openPreview(item.url)" :underline="false">{{ item.name }}</el-link>
                </el-tooltip>
              </div>
            </div>
          </template>

          <!-- 毕业证书 -->
          <template #gradCert="{row}">
            <div v-if="row.gradCert">
              <div v-for="item in JSON.parse(row.gradCert)">
                <el-tooltip effect="light" placement="right">
                  <template #content>
                    <el-link type="primary" :underline="false" @click="handleClickTag(item.url)">下载</el-link>
                  </template>
                  <el-link type="primary" @click="openPreview(item.url)" :underline="false">{{ item.name }}</el-link>
                </el-tooltip>
              </div>
            </div>
          </template>

          <!-- 社保 -->
          <template #socialSecurity="{row}">
            <div v-if="row.socialSecurity">
              <div v-for="item in JSON.parse(row.socialSecurity)">
                <el-tooltip effect="light" placement="right">
                  <template #content>
                    <el-link type="primary" :underline="false" @click="handleClickTag(item.url)">下载</el-link>
                  </template>
                  <el-link type="primary" @click="openPreview(item.url)" :underline="false">{{ item.name }}</el-link>
                </el-tooltip>
              </div>
            </div>
          </template>

          <template slot="menuLeft">
            <el-button type="danger"
                       size="small"
                       icon="el-icon-delete"
                       plain
                       v-if="permission.people_delete"
                       @click="handleDelete">删 除
            </el-button>
          </template>
        </avue-crud>
      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
import fragmentUpload from '@/components/fragment-upload/main.vue';
import { add, getList, remove, update } from '@/api/business/people';
import { getDictionary } from '@/api/system/dict';
import { dept, getDeptList } from '@/api/system/dept';
import { mapGetters } from 'vuex';
import _ from 'lodash';
import { Burger, Upload } from '@element-plus/icons-vue';
import { getToken } from '@/utils/auth';
import website from '@/config/website';
import { downFile } from '@smallwei/avue';
import { getKKFileViewUrl } from '@/utils/util';

export default {
  components: { Burger, fragmentUpload },
  data() {
    return {
      majors: [{
        dictKey: '',
        dictValue: '全部'
      }],
      // 专业
      majorData: [],
      selectDictKey: '',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        gridBtn: false,
        columnBtn: false,
        searchShowBtn: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: false,
        column: [
          {
            label: '姓名',
            prop: 'name',
            search: true,
            dataType: 'string',
            rules: [{
              required: true,
              message: '请输入姓名',
              trigger: 'blur'
            }]
          },
          {
            label: '公司',
            prop: 'deptId',
            search: true,
            clearable: false,
            filterable: true,
            type: 'select',
            dataType: 'string',
            dicData: [],
            dicUrl: dept.deptListUrl,
            props: {
              label: 'deptName',
              value: 'id'
            },
            rules: [{
              required: true,
              message: '请选择公司',
              trigger: 'blur'
            }]
          },
          {
            label: '专业',
            type: 'select',
            dataType: 'string',
            dicData: [],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            slot: true,
            prop: 'majors',
            search: false,
            clearable: false,
            filterable: true,
            multiple: true,
            collapseTags: true,
            maxCollapseTags: 5,
            limit: 0,
            collapseTagsTooltip: true,
            rules: [{
              required: true,
              message: '请选择专业',
              trigger: 'blur'
            }]
          },
          {
            label: '职称',
            prop: 'jobTitle',
            row: true,
            dataType: 'string',
            rules: [{
              required: true,
              message: '请输入职称',
              trigger: 'blur'
            }]
          },
          {
            label: '身份证',
            prop: 'idCard',
            row: true,
            type: 'upload',
            dataType: 'json',
            props: {
              label: 'name',
              value: 'url'
            },
            propsHttp: {
              res: 'data',
              url: 'link',
              name: 'originalName'
            },
            multiple: true,
            listType: 'text',
            action: '/api/civil-resource/oss/endpoint/put-file',
            rules: [{ required: true, message: '请选择身份证', trigger: 'blur' }]
          },
          {
            label: '注册证书',
            prop: 'regCert',
            type: 'upload',
            dataType: 'json',
            props: {
              label: 'name',
              value: 'url'
            },
            propsHttp: {
              res: 'data',
              url: 'link', name: 'originalName'
            },
            listType: 'text',
            action: '/api/civil-resource/oss/endpoint/put-file',
            rules: [{
              required: false,
              message: '请选择注册证书',
              trigger: 'click'
            }]
          },
          {
            label: '职业证书',
            prop: 'profCert',
            type: 'upload',
            dataType: 'json',
            props: {
              label: 'name',
              value: 'url'
            },
            propsHttp: {
              res: 'data',
              url: 'link',
              name: 'originalName'
            },
            multiple: true,
            listType: 'text',
            action: '/api/civil-resource/oss/endpoint/put-file',
            rules: [{
              required: false,
              message: '请选择职业证书',
              trigger: 'click'
            }]
          },
          {
            label: '毕业证书',
            prop: 'gradCert',
            type: 'upload',
            dataType: 'json',
            props: {
              label: 'name',
              value: 'url'
            },
            propsHttp: {
              res: 'data',
              url: 'link',
              name: 'originalName'
            },
            multiple: true,
            listType: 'text',
            action: '/api/civil-resource/oss/endpoint/put-file',
            rules: [{
              required: false,
              message: '请选择毕业证书',
              trigger: 'click'
            }]
          },
          {
            label: '社保',
            prop: 'socialSecurity',
            type: 'upload',
            dataType: 'json',
            props: {
              label: 'name',
              value: 'url'
            },
            propsHttp: {
              res: 'data',
              url: 'link',
              name: 'originalName'
            },
            multiple: true,
            listType: 'text',
            action: '/api/civil-resource/oss/endpoint/put-file',
            rules: [{
              required: false,
              message: '请选择社保',
              trigger: 'click'
            }]
          }
        ]
      },
      data: []
    };
  },
  computed: {
    uploadIcon() {
      return Upload;
    },
    ...mapGetters(['permission', 'userInfo']),
    headers() {
      const token = getToken();
      const headers = {};
      headers[website.Authorization] = 'bearer ' + token;
      return headers;
    },
    permissionList() {
      return {
        addBtn: this.validData(this.permission.people_add, false),
        viewBtn: this.validData(this.permission.people_view, false),
        delBtn: this.validData(this.permission.people_delete, false),
        editBtn: this.validData(this.permission.people_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    getDeptList().then(res => {
      const column = this.findObject(this.option.column, 'deptId');
      column.dicData = res.data.data;
    });

    getDictionary('major').then(res => {
      const column = this.findObject(this.option.column, 'majors');
      column.dicData = res.data.data;
      const cloneData = _.cloneDeep(res.data.data);
      this.majorData = cloneData;
      this.majors = this.majors.concat(cloneData);
    });
  },
  methods: {
    openPreview(previewUrl) {
      const encodeUrl = getKKFileViewUrl(previewUrl);
      window.open(encodeUrl);
    },
    uploadError(error, column) {
      console.log(error);
    },
    handleClickTag(url) {
      downFile(url);
    },
    majorChanged(item) {
      this.selectDictKey = item.dictKey;
      this.page.currentPage = 1;
      this.query = { majors: item.dictKey };
      this.onLoad(this.page, this.query);
    },
    rowSave(row, done, loading) {
      const column = this.findObject(this.option.column, 'deptId');
      let dept = column.dicData.find(v => v.id === row.deptId);
      row.deptName = dept?.deptName;
      // row.idCard = this.form.idCard;
      // row.regCert = this.form.regCert;
      // row.profCert = this.form.profCert;
      // row.gradCert = this.form.gradCert;
      // row.socialSecurity = this.form.socialSecurity;

      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      // if (['edit', 'view'].includes(type)) {
      //   getDetail(this.form.id).then(res => {
      //     this.form = res.data.data;
      //   });
      // }
      done();
    },
    searchResetData() {
      this.selectDictKey = '';
    },
    searchReset() {
      this.searchResetData();

      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = Number(data.total);
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>
<style lang="scss">
.popover-title {
  font-size: 14px;
  padding: 6px 4px;
  border-bottom: 1px double #e7dede;
  cursor: pointer;
  border-radius: 4px;
  text-align: center;
}

.tag-cursor {
  cursor: pointer;
}
</style>
